package com.dd.cloud.user.service.sms.xml;

import com.dd.cloud.common.constants.SmsConstants;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.utils.NumberUtils;
import com.dd.cloud.user.mq.MQConfig;
import com.dd.cloud.user.service.common.ICommonService;
import com.dd.cloud.user.service.doctor.IDoctorUserService;
import com.dd.cloud.user.service.news.INewsInfoService;
import com.dd.cloud.user.service.sms.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zk
 */
@Service
@Slf4j
public class SmsServiceImpl implements ISmsService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private IDoctorUserService doctorUserService;
    @Autowired
    private INewsInfoService newsInfoService;

    @Autowired
    private ICommonService commonService;

    /**
     * 发送验证码
     *
     * @param phone
     */
    @Override
    public void sendCode(String phone, Integer flag, HttpServletRequest request, String codeKey, String tuCode, Integer type) {
        if (type == null) {
            type = 0;
        }
        String product = request.getHeader("AesParam");
        if ("true".equals(product)) {
            if (StringUtils.isBlank(codeKey) || StringUtils.isBlank(tuCode)) {
                throw new ZekeException(400, "图形验证不能为空");
            }
            Boolean flag1 = commonService.verifyImageCode(codeKey, tuCode);
            if (!flag1) {
                throw new ZekeException("图形验证码错误,暂不能发送短信");
            }
        }
//        String client = request.getHeader("client");
//        if (!HealthConstants.ClientType.HEALTHAPPLET.equals(client)
//                && !HealthConstants.ClientType.HEALTHPATIENT.equals(client)
//                && !HealthConstants.ClientType.HEALTHMOB.equals(client)&& type == 1) {

//        }
        if (StringUtils.isAllBlank(phone)) {
            throw new ZekeException(400, "手机号不能为空");
        }
        // 生成key
        String key = SmsConstants.PHONE_KEY_PREFIX + phone;
        if (flag != null) {
            key += ":" + flag;
        }
        int time = 1;
        if (flag != null && flag == 1) {
            time = 30;
        }
        // 生成验证码
        String code = NumberUtils.generateCode(6);
        log.info("发送短信验证码 手机号码:{} 验证码:{}", phone, code);
        Map<String, String> msg = new HashMap<>(4);
        msg.put("phone", phone);
        msg.put("code", code);
        msg.put("param_type", SmsConstants.ParamType.JSON);
        msg.put("sms_template", SmsConstants.Template.CODE);
        amqpTemplate.convertAndSend(MQConfig.SMS_EXCHANGE, MQConfig.SMS_KEY, msg);
        // 保存验证码到redis中 以供后续验证
        redisTemplate.opsForValue().set(key, code, time, TimeUnit.MINUTES);
        log.info("验证码：{}", code);
    }

    /**
     * 效验验证码
     *
     * @param phone
     * @param code
     * @param flag
     */
    @Override
    public void verifyCode(String phone, String code, Integer flag) {
        String cacheKey = SmsConstants.PHONE_KEY_PREFIX + phone;
        if (flag != null) {
            cacheKey += ":" + flag;
        }
        String cacheCode = redisTemplate.opsForValue().get(cacheKey);
        if (!StringUtils.equals(cacheCode, code)) {
            throw new ZekeException(ZkExceptionEnum.INVALID_VERIFY_CODE);
        }
    }

    /**
     * 发送处方订单发货短信给医生
     *
     * @param tencode
     * @param docId
     * @param pName
     * @param expressNo
     * @param expressName
     */
    @Override
    public void sendDeliveryPres(String tencode, Integer docId, String pName, String expressNo, String expressName) {
        String phone = doctorUserService.getDoctorUserPhone(docId);
        String name = doctorUserService.getDoctorUserName(docId);
        Map<String, String> msg = new HashMap<>(7);
        msg.put("phone", phone);
        msg.put("doctorName", name);
        msg.put("medName", pName);
        if (StringUtils.isNotBlank(expressName)) {
            msg.put("express", expressName + "快递");
        } else {
            msg.put("express", "");
        }
        msg.put("expressNo", expressNo);
        msg.put("param_type", SmsConstants.ParamType.JSON);
        msg.put("sms_template", SmsConstants.Template.DELIVERY_PRES);
        amqpTemplate.convertAndSend(MQConfig.SMS_EXCHANGE, MQConfig.SMS_KEY, msg);
        //发送系统消息
        newsInfoService.sendDeliveryPres(tencode, docId, pName, expressNo);
    }
}

